package logic

import (
	"context"
	"time"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePermissionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePermissionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePermissionLogic {
	return &UpdatePermissionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePermissionLogic) UpdatePermission(in *backend.UpdatePermissionRequest) (*backend.UpdatePermissionResponse, error) {
	if in.Id == 0 {
		return nil, errorx.Status(errorx.ERROR_PERM_ID_REQUIRED, "")
	}

	var pageSize int64 = 2
	permissionList, _, err := l.svcCtx.BackendPermission.GetList(l.ctx, model.M{
		model.BackendPermissionColumns.Name: in.Name,
		"pageSize":                          pageSize,
		"select":                            ",",
	}, -1)
	if err != nil {
		return nil, err
	}
	count := len(permissionList)
	if count > 1 {
		return nil, errorx.Status(errorx.ERROR_PERM_NAME_EXISTS, "")
	}
	if count == 1 && permissionList[0].PermissionID != uint64(in.Id) {
		return nil, errorx.Status(errorx.ERROR_PERM_NAME_EXISTS, "")
	}

	var perm model.BackendPermission
	perm.PermissionID = uint64(in.Id)
	perm.Name = in.Name
	perm.Note = in.Note
	perm.Status = uint8(in.Status)
	perm.DelStatus = uint8(in.Status)
	perm.LastUpdatedBy = uint64(in.UpdatedBy)
	perm.UpdatedAt = time.Now()
	_, err = l.svcCtx.BackendPermission.Update(l.ctx, &perm)
	if err != nil {
		return nil, err
	}

	return &backend.UpdatePermissionResponse{}, nil
}
